package com.itHaipeng.service.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;

/**
 * 和事物管理相关的工具类，它包含了开启事物，提交事物，回滚事物，和释放连接
 */
@Service(value = "transactionManager")
public class TransactionManager {
    @Autowired
    private ConnectionUtil connectionUtil;
    /**
     * 开启事物
     */
    public void openTransaction(){
        try {
            connectionUtil.getThreadConnection().setAutoCommit(false);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    //提交事物
    public void commitTransaction() throws SQLException {
        connectionUtil.getThreadConnection().commit();
    }
    //事物回滚
    public void rollbackTransaction()  {
        try {
            connectionUtil.getThreadConnection().rollback();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    //释放连接
    public void closeTransaction()  {
        try {
            connectionUtil.getThreadConnection().close();
            //解除绑定
            connectionUtil.unbindingConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
